<template>
  <div class="house-search-container">
    <!-- 背景装饰元素 -->
    <div class="background-decoration">
      <!-- 精美的动态背景 -->
      <div class="dynamic-background">
        <div class="building building-1"></div>
        <div class="building building-2"></div>
        <div class="building building-3"></div>
        <div class="building building-4"></div>
        <div class="building building-5"></div>
        <div class="cloud cloud-1"></div>
        <div class="cloud cloud-2"></div>
        <div class="cloud cloud-3"></div>
        <div class="sun"></div>
        <div class="light-ray ray-1"></div>
        <div class="light-ray ray-2"></div>
        <div class="light-ray ray-3"></div>
      </div>

      <!-- 浮动装饰元素 -->
      <div class="floating-shape shape-1"></div>
      <div class="floating-shape shape-2"></div>
      <div class="floating-shape shape-3"></div>
      <div class="floating-shape shape-4"></div>
      <div class="floating-shape shape-5"></div>
      <div class="floating-shape shape-6"></div>
    </div>

    <div class="search-wrapper">
      <!-- 搜索区域 -->
      <div class="search-header">
        <h1 class="page-title">房源搜索</h1>
        <div class="search-box">
          <el-input
              v-model="searchKeyword"
              placeholder="请输入区域、地铁站或房源名称"
              size="large"
              class="search-input"
          >
            <template #prepend>
              <el-select v-model="searchType" style="width: 120px">
                <el-option label="区域" value="area"></el-option>
                <el-option label="地铁站" value="subway"></el-option>
                <el-option label="房源名称" value="name"></el-option>
              </el-select>
            </template>
            <template #append>
              <el-button type="primary" icon="Search" @click="searchHouses">搜索</el-button>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 筛选和结果区域 -->
      <div class="search-content">
        <!-- 筛选面板 -->
        <div class="filter-panel">
          <div class="filter-section">
            <h3>位置</h3>
            <el-cascader
                v-model="selectedLocation"
                :options="locationOptions"
                :props="{ expandTrigger: 'hover' }"
                placeholder="请选择位置"
                clearable
                class="filter-item"
            />
          </div>

          <div class="filter-section">
            <h3>价格范围</h3>
            <el-slider
                v-model="priceRange"
                range
                :min="0"
                :max="20000"
                :step="500"
                show-stops
                class="filter-item"
            />
            <div class="price-display">
              <span>¥{{ priceRange[0] }}</span>
              <span>¥{{ priceRange[1] }}</span>
            </div>
          </div>

          <div class="filter-section">
            <h3>户型</h3>
            <el-checkbox-group v-model="selectedLayouts" class="filter-item">
              <el-checkbox v-for="layout in layouts" :key="layout.value" :label="layout.value">
                {{ layout.label }}
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <div class="filter-section">
            <h3>租赁方式</h3>
            <el-radio-group v-model="rentType" class="filter-item">
              <el-radio :label="0">不限</el-radio>
              <el-radio :label="1">整租</el-radio>
              <el-radio :label="2">合租</el-radio>
            </el-radio-group>
          </div>

          <div class="filter-section">
            <h3>朝向</h3>
            <el-select v-model="selectedOrientation" placeholder="请选择朝向" clearable class="filter-item">
              <el-option
                  v-for="item in orientations"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </div>

          <div class="filter-actions">
            <el-button type="primary" @click="applyFilters">应用筛选</el-button>
            <el-button @click="resetFilters">重置筛选</el-button>
          </div>
        </div>

        <!-- 结果区域 -->
        <div class="results-panel">
          <!-- 排序和视图切换 -->
          <div class="results-header">
            <div class="results-count">
              找到 <span class="count-number">{{ totalHouses }}</span> 套房源
            </div>
            <div class="results-controls">
              <el-select v-model="sortBy" placeholder="排序方式" style="width: 150px; margin-right: 15px;">
                <el-option label="默认排序" value="default"></el-option>
                <el-option label="价格从低到高" value="priceAsc"></el-option>
                <el-option label="价格从高到低" value="priceDesc"></el-option>
                <el-option label="面积从大到小" value="areaDesc"></el-option>
              </el-select>
              <el-button-group>
                <el-button :type="viewMode === 'grid' ? 'primary' : ''" @click="viewMode = 'grid'">
                  <el-icon><Grid /></el-icon>
                </el-button>
                <el-button :type="viewMode === 'list' ? 'primary' : ''" @click="viewMode = 'list'">
                  <el-icon><List /></el-icon>
                </el-button>
              </el-button-group>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>

          <!-- 房源列表 -->
          <div v-else class="house-list" :class="viewMode">
            <div
                class="house-item"
                v-for="house in houseList"
                :key="house.houseId"
                @click="viewHouseDetail(house.houseId)"
            >
              <div class="house-image">
                <img :src="house.image || 'https://via.placeholder.com/300x200?text=房源图片'" :alt="house.houseSummary">
                <div class="house-price">¥{{ house.rent }}/月</div>
              </div>
              <div class="house-info">
                <h3 class="house-title">{{ house.houseSummary }}</h3>
                <p class="house-location">
                  <el-icon><Location /></el-icon>
                  {{ house.houseLocation }}
                </p>
                <div class="house-meta">
                  <span>{{ getLayoutLabel(house.layout) }}</span>
                  <span>{{ getAreaByLayout(house.layout) }}㎡</span>
                  <span>{{ house.orientation }}</span>
                </div>
                <div class="house-tags">
                  <el-tag v-if="house.subwayInfo" size="small" type="info">{{ house.subwayInfo }}</el-tag>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="!loading && houseList.length === 0" class="empty-state">
            <el-empty description="暂无符合条件的房源" />
          </div>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                :total="totalHouses"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import {
  Location,
  Grid,
  List
} from '@element-plus/icons-vue'

const router = useRouter()

// 搜索相关数据
const searchKeyword = ref('')
const searchType = ref('area')

// 筛选相关数据
const selectedLocation = ref([])
const priceRange = ref([0, 20000])
const selectedLayouts = ref([])
const rentType = ref(0)
const selectedOrientation = ref('')

// 排序和视图
const sortBy = ref('default')
const viewMode = ref('grid')
const currentPage = ref(1)
const pageSize = ref(10)
const totalHouses = ref(0)
const loading = ref(false)

// 用户位置信息
const userLocation = ref({
  longitude: 115.91,
  latitude: 28.68
})

// 位置选项
const locationOptions = ref([
  {
    value: '江西省',
    label: '江西省',
    children: [
      {
        value: '南昌市',
        label: '南昌市',
        children: [
          { value: '东湖区', label: '东湖区' },
          { value: '西湖区', label: '西湖区' },
          { value: '青云谱区', label: '青云谱区' },
          { value: '青山湖区', label: '青山湖区' },
          { value: '新建区', label: '新建区' },
          { value: '红谷滩区', label: '红谷滩区' }
        ]
      }
    ]
  },
  {
    value: '北京市',
    label: '北京市',
    children: [
      {
        value: '北京市',
        label: '北京市',
        children: [
          { value: '东城区', label: '东城区' },
          { value: '西城区', label: '西城区' },
          { value: '朝阳区', label: '朝阳区' },
          { value: '海淀区', label: '海淀区' }
        ]
      }
    ]
  }
])

// 户型选项
const layouts = ref([
  { value: 1, label: '一居室' },
  { value: 2, label: '两居室' },
  { value: 3, label: '三居室' },
  { value: 4, label: '四居室及以上' }
])

// 朝向选项
const orientations = ref([
  { value: '东', label: '东' },
  { value: '西', label: '西' },
  { value: '南', label: '南' },
  { value: '北', label: '北' },
  { value: '东南', label: '东南' },
  { value: '东北', label: '东北' },
  { value: '西南', label: '西南' },
  { value: '西北', label: '西北' }
])

// 房源列表数据
const houseList = ref([])

// 组件挂载时获取用户位置并搜索房源
onMounted(() => {
  getUserLocation()
})

// 获取用户地理位置
const getUserLocation = () => {
  // 检查是否支持浏览器地理定位API
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        (position) => {
          // 定位成功
          userLocation.value.longitude = position.coords.longitude
          userLocation.value.latitude = position.coords.latitude
          ElMessage.success('定位成功')
          // 获取位置后自动搜索附近房源
          searchHouses()
        },
        (error) => {
          // 定位失败，使用默认位置
          ElMessage.warning(`定位失败: ${error.message}，使用默认位置`)
          searchHouses()
        },
        {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 60000
        }
    )
  } else {
    // 浏览器不支持地理定位
    ElMessage.warning('您的浏览器不支持地理定位，使用默认位置')
    searchHouses()
  }
}

// 搜索房源
const searchHouses = async () => {
  loading.value = true
  try {
    // 构造查询参数
    const requestParams = {
      longitude: userLocation.value.longitude,
      latitude: userLocation.value.latitude,
      radius: 5000, // 5公里范围
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    // 添加筛选条件
    if (selectedLayouts.value.length > 0) {
      requestParams.layout = selectedLayouts.value[0]
    }

    if (priceRange.value[0] > 0) {
      requestParams.rentMin = priceRange.value[0]
    }

    if (priceRange.value[1] < 20000) {
      requestParams.rentMax = priceRange.value[1]
    }

    if (rentType.value !== 0) {
      requestParams.houseRentType = rentType.value
    }

    if (selectedOrientation.value) {
      requestParams.orientation = selectedOrientation.value
    }

    // 调用后端接口
    const response = await axios.post('/house/selectNearbyWithPage', requestParams)

    // 更新房源列表数据
    houseList.value = response.data.data

    // 更新分页信息
    totalHouses.value = response.data.total

    ElMessage.success(`找到 ${response.data.total} 套房源`)
  } catch (error) {
    ElMessage.error('搜索失败，请稍后重试')
    console.error('搜索房源失败:', error)
    houseList.value = []
    totalHouses.value = 0
  } finally {
    loading.value = false
  }
}

// 应用筛选
const applyFilters = () => {
  currentPage.value = 1 // 重置到第一页
  searchHouses()
}

// 重置筛选
const resetFilters = () => {
  selectedLocation.value = []
  priceRange.value = [0, 20000]
  selectedLayouts.value = []
  rentType.value = 0
  selectedOrientation.value = ''
  currentPage.value = 1
  ElMessage.info('筛选条件已重置')
  searchHouses()
}

// 查看房源详情
const viewHouseDetail = (id) => {
  router.push(`/house-detail/${id}`)
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  searchHouses() // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  searchHouses() // 重新加载数据
}

// 根据layout值获取标签
const getLayoutLabel = (layout) => {
  const layoutMap = {
    1: '一居室',
    2: '两居室',
    3: '三居室',
    4: '四居室及以上'
  }
  return layoutMap[layout] || '未知户型'
}

// 根据layout估算面积
const getAreaByLayout = (layout) => {
  const areaMap = {
    1: 60,
    2: 80,
    3: 100,
    4: 120
  }
  return areaMap[layout] || 60
}
</script>

<style scoped>
.house-search-container {
  display: flex;
  min-height: 100vh;
  overflow: hidden;
  position: relative;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

/* 精美的动态背景 */
.dynamic-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #1a2980, #26d0ce);
  overflow: hidden;
}

/* 建筑物 */
.building {
  position: absolute;
  bottom: 0;
  background: rgba(30, 30, 50, 0.8);
  border-radius: 5px 5px 0 0;
  box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
}

.building-1 {
  left: 10%;
  width: 80px;
  height: 300px;
  animation: buildingGlow 4s infinite alternate;
}

.building-2 {
  left: 25%;
  width: 120px;
  height: 400px;
  animation: buildingGlow 5s infinite alternate-reverse;
}

.building-3 {
  left: 45%;
  width: 100px;
  height: 350px;
  animation: buildingGlow 6s infinite alternate;
}

.building-4 {
  left: 65%;
  width: 140px;
  height: 450px;
  animation: buildingGlow 4.5s infinite alternate-reverse;
}

.building-5 {
  left: 80%;
  width: 90px;
  height: 320px;
  animation: buildingGlow 5.5s infinite alternate;
}

@keyframes buildingGlow {
  0% {
    box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
  }
  100% {
    box-shadow: 0 -5px 25px rgba(100, 200, 255, 0.6);
  }
}

/* 云朵 */
.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  filter: blur(2px);
}

.cloud-1 {
  top: 20%;
  left: 5%;
  width: 80px;
  height: 30px;
  animation: cloudMove 25s linear infinite;
}

.cloud-2 {
  top: 35%;
  left: 70%;
  width: 120px;
  height: 40px;
  animation: cloudMove 30s linear infinite;
}

.cloud-3 {
  top: 15%;
  left: 40%;
  width: 100px;
  height: 35px;
  animation: cloudMove 35s linear infinite;
}

@keyframes cloudMove {
  0% {
    transform: translateX(-100px);
  }
  100% {
    transform: translateX(calc(100vw + 100px));
  }
}

/* 太阳 */
.sun {
  position: absolute;
  top: 80px;
  right: 100px;
  width: 80px;
  height: 80px;
  background: radial-gradient(circle, #ffeb3b, #ffc107);
  border-radius: 50%;
  box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  animation: sunPulse 3s infinite alternate;
}

@keyframes sunPulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  }
  100% {
    transform: scale(1.1);
    box-shadow: 0 0 60px #ff9800, 0 0 100px #ff5722;
  }
}

/* 光线 */
.light-ray {
  position: absolute;
  top: 120px;
  right: 140px;
  width: 400px;
  height: 200px;
  background: linear-gradient(to right, transparent, rgba(255, 235, 59, 0.2), transparent);
  transform-origin: left center;
  animation: rayRotate 10s infinite linear;
}

.ray-1 {
  transform: rotate(0deg);
  animation-delay: 0s;
}

.ray-2 {
  transform: rotate(60deg);
  animation-delay: 2s;
}

.ray-3 {
  transform: rotate(120deg);
  animation-delay: 4s;
}

@keyframes rayRotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 浮动装饰元素 */
.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 15s infinite linear;
}

.shape-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  left: -100px;
  animation-duration: 20s;
  background: radial-gradient(circle, rgba(74, 144, 226, 0.2) 0%, transparent 70%);
}

.shape-2 {
  width: 200px;
  height: 200px;
  bottom: -80px;
  right: -80px;
  animation-duration: 25s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 107, 107, 0.2) 0%, transparent 70%);
}

.shape-3 {
  width: 150px;
  height: 150px;
  top: 30%;
  right: 20%;
  animation-duration: 15s;
  background: radial-gradient(circle, rgba(80, 227, 194, 0.2) 0%, transparent 70%);
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-duration: 18s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 209, 102, 0.2) 0%, transparent 70%);
}

.shape-5 {
  width: 250px;
  height: 250px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-duration: 22s;
  background: radial-gradient(circle, rgba(155, 89, 182, 0.2) 0%, transparent 70%);
}

.shape-6 {
  width: 180px;
  height: 180px;
  top: 70%;
  left: 10%;
  animation-duration: 28s;
  background: radial-gradient(circle, rgba(231, 76, 60, 0.2) 0%, transparent 70%);
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(20px, 20px) rotate(90deg);
  }
  50% {
    transform: translate(0, 40px) rotate(180deg);
  }
  75% {
    transform: translate(-20px, 20px) rotate(270deg);
  }
  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.search-wrapper {
  width: 100%;
  max-width: 1400px;
  margin: 20px auto;
  z-index: 1;
  position: relative;
  padding: 0 20px;
}

.search-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-title {
  color: white;
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 30px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.search-box {
  max-width: 800px;
  margin: 0 auto;
}

.search-input {
  width: 100%;
}

.search-content {
  display: flex;
  gap: 30px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
}

.filter-panel {
  width: 250px;
  flex-shrink: 0;
  background: #f8f9fa;
  border-radius: 10px;
  padding: 20px;
  height: fit-content;
}

.filter-section {
  margin-bottom: 25px;
}

.filter-section h3 {
  margin: 0 0 15px;
  font-size: 18px;
  color: #2c3e50;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.filter-item {
  width: 100%;
}

.price-display {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 14px;
  color: #7f8c8d;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.results-panel {
  flex: 1;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.results-count {
  font-size: 16px;
  color: #7f8c8d;
}

.count-number {
  font-weight: 700;
  color: #409EFF;
}

.loading-container {
  padding: 20px 0;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.house-list.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.house-list.list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 30px;
}

.house-item {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
}

.house-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.house-list.grid .house-item {
  display: flex;
  flex-direction: column;
}

.house-list.list .house-item {
  display: flex;
  flex-direction: row;
}

.house-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.house-list.list .house-image {
  width: 300px;
  flex-shrink: 0;
}

.house-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.house-item:hover .house-image img {
  transform: scale(1.05);
}

.house-price {
  position: absolute;
  top: 15px;
  right: 15px;
  background: rgba(74, 144, 226, 0.9);
  color: white;
  padding: 5px 10px;
  border-radius: 20px;
  font-weight: 600;
  font-size: 14px;
}

.house-info {
  padding: 20px;
  flex: 1;
}

.house-title {
  margin: 0 0 10px;
  font-size: 18px;
  font-weight: 700;
  color: #2c3e50;
}

.house-location {
  display: flex;
  align-items: center;
  gap: 5px;
  margin: 0 0 15px;
  font-size: 14px;
  color: #7f8c8d;
}

.house-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
  font-size: 13px;
  color: #7f8c8d;
}

.house-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

@media (max-width: 1200px) {
  .search-content {
    flex-direction: column;
  }

  .filter-panel {
    width: 100%;
  }

  .results-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .results-controls {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}

@media (max-width: 768px) {
  .search-wrapper {
    margin: 10px;
    padding: 10px;
  }

  .search-content {
    padding: 15px;
  }

  .house-list.grid {
    grid-template-columns: 1fr;
  }

  .house-list.list .house-item {
    flex-direction: column;
  }

  .house-list.list .house-image {
    width: 100%;
    height: 200px;
  }

  .results-controls {
    flex-direction: column;
    gap: 10px;
  }

  .filter-actions {
    flex-direction: column;
  }
}
</style>
